/** */
package com.hotau.util;

import android.app.ProgressDialog;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.util.Log;

import com.hotau.Executable;
import com.hotau.HotauActivity;
import com.hotau.HotauConstants;
import com.hotau.HttpTimeoutFragment;
import com.hotau.NavigationActivity;
import com.hotau.member.LoginFragment;
import com.hotau.member.service.MemberService;

/**
 * @author fengweili</br> 2011-8-12 上午09:36:56
 */
public abstract class HttpRequestAsynTask extends GeneralAsynTask {

	/**
	 * @param context
	 */
	protected Context context;

	public HttpRequestAsynTask(Context context) {
		super(context);
		this.context = context;
	}

	public HttpRequestAsynTask(Context context, boolean alertResultNull) {
		super(context, alertResultNull);
	}

	public HttpRequestAsynTask(Context context, String prompt) {
		super(context, prompt);
		this.context = context;
	}

	public HttpRequestAsynTask(Context context, ProgressDialog progressDialog) {
		super(context, progressDialog);
		this.context = context;
	}

	// 此方法在UI线程中执行
	// 当后台计算结束时，调用 UI线程。后台计算结果作为一个参数传递到这步
	@Override
	protected void onPostExecute(String result) {
		super.onPostExecute(result);

		if(stopped)
		{
		    return;
		}
		
		if (result == null || "".equals(result)) {
			DialogUtil.showDialog(context, "", "网络无法连接，信息读取失败。",
					new Executable() {
						@Override
						public void execute() {
							// 弹出
							NavigationActivity activity = (NavigationActivity) context;

							Fragment fragment = activity.fragmentStack.peek();
							if (fragment instanceof HttpTimeoutFragment) {
								HttpTimeoutFragment http_fragment = (HttpTimeoutFragment) fragment;
								if (http_fragment.needPopWhenTimeout()) {
									try {
										activity.popFragment();
									} catch (Exception ex) {
										ex.printStackTrace();
										Log.e("mytag", "弹出碎片失败");
									}
								} else {
									// do nothing
								}
							}

						}
					});
			return;
		}
		
		else if(result.equals("403"))
        {
            MemberService.logout(context);
            DialogUtil.showDialog(context, "", "系统超时请重新登陆",new Executable(){
				@Override
				public void execute() {
					// TODO Auto-generated method stub
					HotauActivity ha = (HotauActivity) context;
					ha.pushFragment("登录", new LoginFragment());
				}
            });
            return;
        }

		if (!stopped){
			doPostExecute(result);
		}
	}

	@Override
	protected String doInBackground(String... params) {
		String result = "测试结果";
		if (!HotauConstants.DEMO) {
			result = HttpUtil.doWrapedHttp(context, params);
		}

		return result;
	}

}
